# make-cert.ps1
# 以管理员身份运行！证书将输出到脚本所在目录
param(
    [string]$DnsList = "localhost,127.0.0.1",   # 可在外部用 -DnsList "a.com,b.com" 覆盖
    [string]$CertPwd = "1234"                  # pfx 密码
)

$ErrorActionPreference = "Stop"
$root = $PSScriptRoot                       # 脚本所在目录
if (-not $root) { $root = (Get-Location).Path }

# 1. 生成自签名证书（到 LocalMachine\My 存储）
$dns = $DnsList -split ','                  # 支持多个域名/IP
$cert = New-SelfSignedCertificate `
          -DnsName $dns `
          -CertStoreLocation "cert:\LocalMachine\My" `
          -KeyExportPolicy Exportable `
          -KeySpec Signature `
          -KeyLength 2048

$thumb = $cert.Thumbprint
Write-Host "已生成证书，Thumbprint：$thumb"

# 2. 导出 PFX 到脚本目录
$pfxFile = Join-Path $root "localhost.pfx"
$securePwd = ConvertTo-SecureString -String $CertPwd -Force -AsPlainText
Export-PfxCertificate -Cert "cert:\LocalMachine\My\$thumb" `
                      -FilePath $pfxFile `
                      -Password $securePwd | Out-Null
Write-Host "PFX 已导出到：$pfxFile"

# 3. 把证书也导成 PEM 格式（公钥 + 私钥）
#    使用 .NET 自带的 Export 方法，无需 OpenSSL
$bytes = $cert.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert)
$cerFile = Join-Path $root "localhost.crt"
[System.IO.File]::WriteAllBytes($cerFile, $bytes)
Write-Host "公钥已导出到：$cerFile"

# 私钥
$rsa = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($cert)
$keyBytes = $rsa.Key.Export([System.Security.Cryptography.CngKeyBlobFormat]::Pkcs8PrivateBlob)
$keyFile = Join-Path $root "localhost.key"
[System.IO.File]::WriteAllBytes($keyFile, $keyBytes)
Write-Host "私钥已导出到：$keyFile"

Write-Host "`n全部完成！文件列表："
Get-ChildItem $root -Name "localhost.*"